from selenium import webdriver
from selenium.webdriver.chrome.service import Service
from PO项目实战.驱动层 import browser_name, driver_path, headless_mode


class WebdriverConf():

    def __init__(self):
        """
        :param browser_name: 浏览器名
        :param driver_path: 浏览器driver存放位置
        :param headless_mode: 是否无痕模式
        """
        self.driver = self.get_driver(browser_name, driver_path, headless_mode)

    # 设置浏览器，获取driver
    def get_driver(self, browser_name, driver_path=None, headless_mode=False):
        # 根据配置构建WebDriver实例
        if browser_name.lower() == 'chrome':
            # Options对象设置用例执行后是否关闭
            options = webdriver.ChromeOptions()
            options.add_experimental_option('detach', True)  # 设置浏览器不关闭
            # Service对象设置浏览器驱动地址
            service = Service(executable_path=driver_path)
            if headless_mode:
                # Options对象设置无头模式
                options.add_argument('--headless')
            # 创建WebDriver实例
            driver = webdriver.Chrome(service=service, options=options)
        elif browser_name.lower() == 'firefox':
            ff_options = webdriver.FirefoxOptions()
            service = Service(executable_path=driver_path)
            if headless_mode:
                ff_options.add_argument("--headless")
            driver = webdriver.Firefox(service=service, options=ff_options)
        else:
            driver = None
        return driver

    # 关闭当前浏览器窗口
    def close_current_window(self):
        self.driver.close()

    # 关闭浏览器
    def close_browser(self):
        self.driver.quit()
        